package models

import (
	"errors"
	"path/filepath"
	"time"

	"gorm.io/gorm"
)

type FileInfo struct {
	ID       uint `gorm:"primarykey"`
	Dir      string
	FileName string
	//脱敏标志位
	DesensitStatus bool
	//解析标志位
	AsDicomStatus bool
	CreatedAt     time.Time
	UpdatedAt     time.Time
}

func NewFileInfo(file string) *FileInfo {
	dir, file := filepath.Split(file)
	return &FileInfo{
		Dir:      dir,
		FileName: file,
		//默认创建时脱敏为false
		DesensitStatus: false,
		AsDicomStatus:  false,
	}
}

//单条查询
func (f *FileInfo) GetStatusOne(status bool) *FileInfo {
	err := DBConn.Where("AsDicomStatus = ?", status).Take(&f).Error
	if err != nil {
		//查询不到 视为查询结束
		if errors.Is(err, gorm.ErrRecordNotFound) {
			Log.INFO("查询结束")
			return nil
		} else {
			//若是其他查询错误，暂缓1秒查询
			Log.WARNING("%w", err)
			time.Sleep(time.Second)
			f.GetStatusOne(status)
		}
	}

	return &FileInfo{}

}

//迭代查询
//func (f *FileInfo) GetRows(status bool) (*sql.Rows, error) {
//	rows, err := DBConn.Model(f).Rows()
//	if err != nil {
//		Log.ERROR(err.Error())
//		return nil, err
//	}
//	return rows, nil
//
//}

//查询多行
func (f *FileInfo) GetRows(num int) (int64, []*FileInfo) {
	var rows []*FileInfo
	result := DBConn.Limit(num).Where("as_dicom_status = ?", false).Find(&rows)
	Log.DEBUG("fileinfo查询完成，本次查询%d", result.RowsAffected)
	return result.RowsAffected, rows
}

func (f *FileInfo) clear() {
	DBConn.Exec("DELETE FROM file_infos")
	Log.WARNING("clear DB file_infos table is over~!")
}

func (f *FileInfo) InsertOne() {
	result := DBConn.FirstOrCreate(f, f)
	if result.RowsAffected <= 0 {
		Log.WARNING("文件信息重复: %v", f.FileName)
	}
}

func (f *FileInfo) UpdataAsDicomStatus(status bool) {
	f.AsDicomStatus = status
	DBConn.Model(f).Update("AsDicomStatus", status)
	//DBConn.Save(f)
}

//func UpdataAsDicomStatus(FileInfoID uint, status bool) {
//	DBConn.Model(&FileInfo{}).Where("ID", FileInfoID).Update("AsDicomStatus", status)
//	//DBConn.Save(f)
//}

func (f *FileInfo) Count() int64 {
	var count int64
	DBConn.Table("file_infos").Count(&count)
	return count
}

//统计数据中dicom信息
func CountFileFromDB() int64 {
	var c int64
	DBConn.Raw("select count(*) from file_infos").Scan(&c)
	return c
}
